package org.scratchcrew.domain.dao;

import org.scratchcrew.domain.BaseEntity;
import org.scratchcrew.domain.SoftDeletable;
import org.springframework.orm.jpa.support.JpaDaoSupport;

public class EntityDaoSupport<T extends BaseEntity> extends JpaDaoSupport
		implements EntityDao<T> {
	private Class<T> entityClass;

	public EntityDaoSupport(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	@Override
	public void delete(T entity) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Deleting entity of %s type %s",
					entityClass.getName(), entity));
		}
		if (entity instanceof SoftDeletable) {
			((SoftDeletable) entity).markAsDeleted();
			getJpaTemplate().persist(entity);
		} else {
			getJpaTemplate().remove(entity);
		}
	}

	@Override
	public T find(Long id) {
		T result = getJpaTemplate().find(entityClass, id);
		if (result instanceof SoftDeletable) {
			return ((SoftDeletable) result).isDeleted() ? null : result;
		}
		return result;
	}

	@Override
	public T save(T entity) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Saving entity of %s type %s",
					entityClass.getName(), entity));
		}
		getJpaTemplate().persist(entity);
		return entity;
	}
	
}
